package com.smartrodin.springbootrabbitmq.config;

import com.smartrodin.springbootrabbitmq.util.Constant;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: arnold_nie
 * @date: 2020/7/25 16:42
 * FileName: DelayQueueConfig
 * Description: 延迟队列配置
 */
@Configuration
public class DelayQueueConfig {

    /**
     * 交换机与队列绑定的RoutingKey
     */
    private static final String ROUTING_KEY_DELAY_QUEUE = "routingKey.delayQueue";
    private static final String ROUTING_KEY_DEAD_LETTER_QUEUE = "routingKey.deadLetterQueue";

    /**
     * 创建延迟队列交换机
     *
     * @return the exchange
     */
    @Bean(Constant.DELAY_QUEUE_EXCHANGE)
    public Exchange delayQueueExchange() {
        return ExchangeBuilder.directExchange( Constant.DELAY_QUEUE_EXCHANGE ).durable( true ).build();
    }

    /**
     * 创建死信队列交换机
     *
     * @return the exchange
     */
    @Bean(Constant.DEAD_LETTER_QUEUE_EXCHANGE)
    public Exchange deadLetterQueueExchange() {
        return ExchangeBuilder.directExchange( Constant.DEAD_LETTER_QUEUE_EXCHANGE ).durable( true ).build();
    }

    /**
     * 延迟队列
     *
     * @return
     */
    @Bean(Constant.QUEUE_DELAY)
    public Queue delayQueue() {
        Map<String, Object> params = new HashMap<>();
        // x-dead-letter-exchange 声明了队列里的死信转发到的DLX名称，
        params.put("x-dead-letter-exchange", Constant.DEAD_LETTER_QUEUE_EXCHANGE);
        // x-dead-letter-routing-key 声明了这些死信在转发时携带的 routing-key 名称。
        params.put("x-dead-letter-routing-key", ROUTING_KEY_DEAD_LETTER_QUEUE);
        return new Queue(Constant.QUEUE_DELAY, true, false, false, params);
    }

    /**
     * 死信队列
     *
     * @return
     */
    @Bean(Constant.QUEUE_DEAD_LETTER)
    public Queue deadLetterQueue() {
        return new Queue( Constant.QUEUE_DEAD_LETTER );
    }

    /**
     *  队列和交换机绑定，并且指定RoutingKey
     */
    @Bean
    public Binding delayQueueBindingDirect(@Qualifier(Constant.QUEUE_DELAY) Queue queue,
                                             @Qualifier(Constant.DELAY_QUEUE_EXCHANGE) Exchange exchange) {
        return BindingBuilder.bind( queue ).to( exchange ).with( ROUTING_KEY_DELAY_QUEUE ).noargs();
    }

    /**
     * 队列和交换机绑定，并且指定RoutingKey
     */
    @Bean
    public Binding deadLetterQueueBindingDirect(@Qualifier(Constant.QUEUE_DEAD_LETTER) Queue queue,
                                                @Qualifier(Constant.DEAD_LETTER_QUEUE_EXCHANGE) Exchange exchange) {
        return BindingBuilder.bind( queue ).to( exchange ).with( ROUTING_KEY_DEAD_LETTER_QUEUE ).noargs();
    }


}
